package com.vicene.gmail.cart.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.vicene.gmail.cart.vo.UserInfoTo;
import com.vicene.gmail.common.constant.CartConstant;
import com.vicene.gmail.common.vo.WeiBoLoginResp;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        WeiBoLoginResp resp = (WeiBoLoginResp) request.getSession().getAttribute("loginUser");
        if(resp != null){
            userInfoTo.setUserId(resp.getId());
        }

        Cookie[]cookies = request.getCookies();
        if(!ArrayUtil.isEmpty(cookies)){
            for(Cookie cookie : cookies){
                String name = cookie.getName();
                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }

        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.isTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME , userInfoTo.getUserKey());
            cookie.setDomain("gmail.com");
            //cookie.setMaxAge();
            response.addCookie(cookie);
        }
    }
}
